package com.wx.web.controller.user;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.eachonline.core.JsonResult;
import com.eachonline.util.RedisHelper;
import com.eachonline.util.StringUtil;
import com.eachonline.util.UUIDUtil;
import com.wx.business.trade.IxbUserService;
import com.wx.business.util.AesCbcUtil;
import com.wx.model.IxbUser;
import com.wx.model.IxbUserExample;
import com.wx.web.common.WXHttpUtil;

/**
 * 微信小程序
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/wxAppUser")
public class WxAppUserInfoController  {
	
	  public static String strurl="http://admin.ixbonline.com/";
	  
	  public static String adminurl="http://www.ixbonline.com/";;
	
	 @Autowired
	 private IxbUserService ixbUserService;
      
	 /**
	  * 获取  code2Session
	  * -1	系统繁忙，此时请开发者稍候再试;    0	请求成功 ; 40029	code 无效 ; 45011	频率限制，每个用户每分钟100次
	  * @param request
	  * @param response
	  * @param jsCode
	  * @return
	  */
	@RequestMapping(value = "/code2Session", method = { RequestMethod.GET })
	@ResponseBody
	public JsonResult code2Session(HttpServletRequest  request ,HttpServletResponse response,String jsCode) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		   if(StringUtils.isEmpty(jsCode))
	        {
	        	 return  new JsonResult(true,"jsCode不能为空");
	        }	
		 
		 String resultJson= WXHttpUtil.requestCode2Session(jsCode);
		 JSONObject object=JSONObject.parseObject(resultJson);
	     if(StringUtil.isEmpty(object.get("errcode")+""))
         {
         	 return  new JsonResult(false,"获取code2Session失败");
         }
	     String errcode=object.get("errcode")+"";
	     
	     if("-1".equals(errcode))
	      return  new JsonResult(false,"系统繁忙，此时请开发者稍候再试");
	     
	     if("40029".equals(errcode))
	    	 return  new JsonResult(false,"code 无效");
	     
	     if("45011".equals(errcode))
	    	 return  new JsonResult(false,"频率限制，每个用户每分钟100次");
	     
	     //返回结果集中
	     // openid	string	用户唯一标识
	     //session_key	string	会话密钥
	     //unionid	string	用户在开放平台的唯一标识符，在满足 UnionID 下发条件的情况下会返回，详见 UnionID 机制说明。
	     
         String openId=object.get("openid")+"";
         String session_key=object.get("session_key")+"";
         String unionid=object.get("unionid")+"";
         Map<String,Object>  resultMap=new HashMap<String,Object>();
         resultMap.put("openId", openId);
         resultMap.put("session_key", session_key);
         resultMap.put("unionid", unionid);
         JsonResult  jresult= new JsonResult(true,"成功",resultMap);
         jresult.setModule("");
         return  jresult;
        
        
        
	}

	
	
	/**
	 * 解密用户信息
	 * @param request
	 * @param iv
	 * @param encryptedData
	 * @param key
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getUserInfo", method = { RequestMethod.POST })
	@ResponseBody
	public JsonResult getUserInfo(HttpServletRequest  request,String iv,String encryptedData ,String key,HttpServletResponse response) throws Exception {
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> userInfo = new HashMap<String,Object>();

        try {
			String result = AesCbcUtil.decrypt(encryptedData, key, iv, "UTF-8");
			if (null != result && result.length() > 0) {
				
				JSONObject userInfoJSON=JSONObject.parseObject(result);
				userInfo.put("openId", userInfoJSON.get("openId"));
				userInfo.put("nickName", userInfoJSON.get("nickName"));
				userInfo.put("gender", userInfoJSON.get("gender"));
				userInfo.put("city", userInfoJSON.get("city"));
				userInfo.put("province", userInfoJSON.get("province"));
				userInfo.put("country", userInfoJSON.get("country"));
				userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
				// 解密unionId & openId;
 
				userInfo.put("unionId", userInfoJSON.get("unionId"));
				resultMap.put("userInfo", userInfo);
				resultMap.put("status", 1);
				resultMap.put("msg", "解密成功");
				
			} else {
				resultMap.put("status", 0);
				resultMap.put("msg", "解密失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return  new JsonResult(false,e.getMessage());
		}
        
        String openId=userInfo.get("openId")+"";
        IxbUserExample userext=new IxbUserExample();
        userext.createCriteria().andOpenidEqualTo(openId);
        List<IxbUser> iuserlist=ixbUserService.selectByExample(userext);
        
        IxbUser ixbUser=null;
        if(iuserlist!=null&&iuserlist.size()>0)
        {
        	 ixbUser=iuserlist.get(0);
        	
        	 if(StringUtils.isNotEmpty(ixbUser.getUserPic())&&!ixbUser.getUserPic().equals(userInfo.get("avatarUrl")+""))
        	 {
        		 ixbUser.setUserPic(userInfo.get("avatarUrl")+"");
            	 ixbUserService.updateByPrimaryKeySelective(ixbUser);

        	 }
        }
        
        if(ixbUser==null)
        {
        	 IxbUser user=new IxbUser();
             user.setSid(UUIDUtil.getUUID());
             user.setCity(userInfo.get("city")+"");
             user.setCountry(userInfo.get("country")+"");
             user.setCreateTime(new Date());
             user.setOpenid(openId);
             user.setProvince(userInfo.get("province")+"");
             user.setSex(Integer.valueOf( userInfo.get("gender")+""));
             user.setUserName(userInfo.get("nickName")+"");
             user.setUserPic(userInfo.get("avatarUrl")+"");
             ixbUserService.insertSelective(user);
             ixbUser=user;
        }
        
        RedisHelper.setObjectExp(ixbUser.getSid(), ixbUser, 3600*24);
        HttpSession  session = request.getSession(true);
      		// end
      	session.setAttribute("currentAccount", ixbUser);
        return  new JsonResult(true, "成功", ixbUser);
       
	}

}
